<template>
  <div class="device-list-container">
    <!-- 查询区域 -->
    <div class="query-area">
      <span>{{ $t('deviceSearch') }}</span>
      <el-input v-model="queryDeviceNumber" clearable :placeholder="$t('inputDeviceNum')"
        style="width: 200px;margin-left: 10px;"></el-input>
      <span style="margin-left: 20px;">{{ $t("state") }}</span>
      <el-select v-model="queryStatus" style="margin-left: 20px;width: 100px;" :placeholder="$t('chooseState')">
        <el-option :label="$t('conn')" value="连接"></el-option>
        <el-option :label="$t('lose')" value="失效"></el-option>
        <el-option :label="$t('all')" value="全部"></el-option>
      </el-select>
      <div style="flex: 1;"></div>
      <div class="query-buttons">
        <el-button round icon="el-icon-search" @click="handleQuery" style="background-color: #5B5F97; color: white;">{{
          $t('search') }}</el-button>
        <el-button icon="el-icon-refresh" round @click="handleReset">{{ $t('reset') }}</el-button>
      </div>
    </div>
    <!-- 统计和操作按钮区域 -->
    <div class="stats-and-buttons">
      <div class="stats">
        <span>{{ $t('total') }} {{ totalDevices }} {{ $t('deviceCount') }}，{{ $t('totalCount') }} {{ newDevicesToday }}
          {{ $t('ge') }}</span>
      </div>
      <div class="buttons">
        <el-button round icon="el-icon-download" @click="downloadAddr"
          style="background-color: #5B5F97; color: white;">{{ $t('download') }}</el-button>
        <el-button round @click="refreshList">{{ $t('refresh') }}</el-button>
      </div>
    </div>
    <!-- 列表区域 -->
    <div class="table-box" ref="parentRef">
      <!-- 设备表格 -->
      <div style="flex: 1;display: flex;flex-direction: column;" :style="'height:' + parentHeight + 'px'">
        <div class="table-wrapper">
          <el-table :data="currentDeviceList" highlight-current-row row-class-name="selected-row" stripe
            ref="deviceTable" @current-change="handleSelectionChange">
            <!-- <el-table-column type="radio" width="55"></el-table-column> -->
            <el-table-column prop="device_number" :label="$t('deviceNum')"></el-table-column>
            <el-table-column prop="device_client" :label="$t('state')">
              <template slot-scope="scope">
                <div style="display: flex;align-items: center;">
                  <span :class="scope.row.device_client ? 'client-conn' : 'client-unconn'">{{ scope.row.device_client ?
                    $t('conn') : $t('lose')
                    }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="device_net" :label="$t('net')"></el-table-column>
            <el-table-column prop="device_type" :label="$t('model')"></el-table-column>
          </el-table>
        </div>
        <!-- 分页组件 -->
        <div class="pagination-wrapper">
          <el-pagination @current-change="handleCurrentChange" :current-page="currentPage" layout=" prev, pager, next">
          </el-pagination>
        </div>
      </div>
      <!-- 消息表格 -->
      <div style="flex: 2;margin-left: 20px;display: flex;flex-direction: column;overflow-y: auto;"
        :style="'height:' + parentHeight + 'px'">
        <div style="padding: 15px;background-color: #e6e6e6;">PHOTO</div>
        <div style="display: flex;flex-wrap: wrap;align-items: flex-start;" ref="photoBox">
          <el-image @click="showBigImage(item.album_img)" class="photo" v-for="item in currentMsgList"
            :style="`width: ${photoWidth}px; height: ${photoWidth}px`" :src="item.album_img" :fit="cover"></el-image>
        </div>
      </div>
    </div>
    <!-- 大图遮罩层 -->
    <div class="overlay" :class="{ show: isBigImageVisible }" @click="hideBigImage">
      <img class="big-img" :src="bigImgUrl" alt="Big Image">
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'
export default {
  data() {
    return {
      queryDeviceNumber: '',
      queryStatus: '全部',
      totalDevices: 0,
      newDevicesToday: 0,
      currentPage: 1,
      currentMsgPage: 1,
      pageSize: 20,
      currentDeviceList: [],
      multipleSelection: [],
      dialogVisible: false,
      smsContent: "",
      receiveNumber: "",
      selectedRow: "",
      receiveNumberList: [],
      currentMsgList: [],
      parentHeight: 0,
      photoWidth: 50,
      bigImgUrl: "",
      isBigImageVisible: false
    };
  },
  created() {
    this.updateCurrentDeviceList();
  },
  mounted() {
    this.parentHeight = this.$refs.parentRef.offsetHeight;
    this.photoWidth = this.$refs.photoBox.offsetWidth / 10;
  },
  methods: {
    showBigImage(url) {
      this.bigImgUrl = url;
      this.isBigImageVisible = true;

    },
    hideBigImage() {
      this.isBigImageVisible = false;
    },
    // 更新当前页的设备列表
    updateCurrentDeviceList() {
      let state = "";
      if (this.queryStatus == "全部") {
        state = ""
      } else if (this.queryStatus == "连接") {
        state = 0;
      } else if (this.queryStatus == "失效") {
        state = 1;
      }
      request({
        url: '/index/api/getClient',
        method: 'get',
        params: { page: this.currentPage, search: this.queryDeviceNumber, state }
      }).then(res => {
        console.log('res', res);
        if (res.status_code == 200) {
          this.currentMsgList = [];
          this.selectedRow = "";
          this.currentDeviceList = res.data.data;
          this.totalDevices = res.data.device_all;
          this.newDevicesToday = res.data.device_today;
          const targetRow = this.currentDeviceList.find(item => item.id === this.$store.state.app.selectedDeviceId);
          if (targetRow) {
            this.$refs.deviceTable.setCurrentRow(targetRow);
          }
        }
      })
    },
    //下载
    downloadAddr() {
      if (!this.selectedRow) {
        this.$message({
          message: this.$t('chooseDevice'),
          type: 'warning'
        })
        return
      }
      request({
        url: "/index/api/getAddrExcel",
        method: 'get',
        params: { device_id: this.selectedRow.id },
        responseType: 'blob' // 设置响应类型为 blob
      }).then(response => {
        // 创建一个 URL 对象
        const url = window.URL.createObjectURL(new Blob([response.data]));
        // 创建一个 <a> 元素
        const link = document.createElement('a');
        link.href = url;
        // 设置下载的文件名
        link.setAttribute('download');
        document.body.appendChild(link);
        // 模拟点击 <a> 元素来触发下载
        link.click();
        // 释放 URL 对象
        window.URL.revokeObjectURL(url);
      }).catch(error => {
        console.error('文件下载失败:', error);
      });
    },
    getRowKey(row) {
      return row.id;
    },
    // 处理查询操作
    handleQuery() {
      this.currentPage = 1;
      this.updateCurrentDeviceList();
    },
    // 处理行点击事件
    handleRowClick(row) {
      // 切换行的选中状态
      // this.$refs.deviceTable.toggleRowSelection(row);
      this.selectedRow = row;
    },
    // 处理行点击事件
    handleMsgRowClick(row) {
      // 切换行的选中状态
      this.$refs.deviceTable.toggleRowSelection(row);
    },
    // 处理重置操作
    handleReset() {
      this.queryDeviceNumber = '';
      this.queryStatus = '';
      this.currentPage = 1;
      this.updateCurrentDeviceList();
    },

    //时间戳格式化
    timestampToDate(timestamp, format = 'YYYY-MM-DD HH:MM:SS', isSeconds = true) {
      if (isSeconds) {
        timestamp = timestamp * 1000;
      }
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      let formattedDate = format;
      formattedDate = formattedDate.replace('YYYY', year);
      formattedDate = formattedDate.replace('MM', month);
      formattedDate = formattedDate.replace('DD', day);
      formattedDate = formattedDate.replace('HH', hours);
      formattedDate = formattedDate.replace('MM', minutes);
      formattedDate = formattedDate.replace('SS', seconds);
      return formattedDate;
    },
    // 刷新列表
    refreshList() {
      this.currentPage = 1;
      this.updateCurrentDeviceList();
      this.$refs.deviceTable.clearSelection();

    },
    // 每页数量改变时触发
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.updateCurrentDeviceList();
    },
    // 当前页码改变时触发
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.updateCurrentDeviceList();
      this.$refs.deviceTable.clearSelection();
    },
    handleMsgCurrentChange(newPage) {
      this.currentMsgPage = newPage;
      this.getMsgList();
      this.$refs.msgTable.clearSelection();
    },
    // 处理表格勾选变化
    handleSelectionChange(row) {
      this.$store.dispatch('app/setSelectedDeviceId', row.id);
      this.selectedRow = row;
      this.currentMsgPage = 1;
      this.getMsgList();
    },
    //查询短信列表
    getMsgList() {
      request({
        url: '/index/api/getAlbum',
        method: 'get',
        params: { device_id: this.selectedRow.id, page: this.currentMsgPage }
      }).then(res => {
        console.log('getAddrList res', res);
        if (res.status_code == 200) {
          this.currentMsgList = res.data;
          // this.totalDevices = res.data.device_all;
          // this.newDevicesToday = res.data.device_today;
        }
      })

    }
  }
};
</script>

<style>
.el-table thead th {
  background-color: #e6e6e6;
  /* 设置表头背景色 */
  color: #111111;
  /* 设置表头文字颜色，使其在深色背景下可见 */
}

.el-table__body tr.current-row>td {
  background-color: #C9CCED;
}

</style>

<style scoped>
.device-list-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 50px);
  padding: 20px;
}

.query-area {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ccc;
  /* 添加分隔线 */
}

.query-buttons {
  display: flex;
}

.query-buttons el-button {
  margin-left: 10px;
}

.stats-and-buttons {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.stats {
  font-size: 14px;
  color: #5B5F97;
}

.buttons {
  display: flex;
}

.buttons el-button {
  margin-left: 10px;
}

.table-wrapper {
  flex: 1;
  overflow-y: auto;
}

.pagination-wrapper {
  padding: 10px;
  background-color: #f5f7fa;
  border-top: 1px solid #e4e7ed;
}

/* 设置表格表头背景色 */
.el-table thead th {
  background-color: #818181;
  color: white;
  /* 为了让文字在深色背景下可见 */
}

/* 设置表格选中条目背景色 */
.el-table__body tr.current-row>td {
  background-color: #C9CCED;
}

.selected-row {
  background-color: red;
}

::v-deep .el-dialog {
  border-radius: 10px;
  width: 50%;
  background-color: white;
}

::v-deep .custom-dialog .el-dialog__header {
  background-color: #5B5F97;
  /* 标题栏背景色为 #5B5F97 */
  border-top-left-radius: 10px;
  padding: 10px;
  /* 标题左上角弧度与弹窗弧度相同 */
  border-top-right-radius: 10px;
  /* 标题右上角弧度与弹窗弧度相同 */
  /* 标题高度为 40px */
  display: flex;
  align-items: center;
  justify-content: center;
}

::v-deep .el-dialog__title {
  color: white;
  /* 标题文字颜色为白色 */
  text-align: center;
  font-size: 18px;
}

.num-list-box {
  margin-top: 15px;
  height: 150px;
  border-radius: 10px;
  background: rgba(91, 95, 151, 0.1);
  padding: 15px;
  overflow-y: auto;
}

.client-conn {
  border-radius: 50px;
  padding: 2px 10px;
  color: #0960BD;
  font-size: 14px;
  border: 1px solid #0960BD;
  text-align: center;
}

.client-unconn {
  border-radius: 50px;
  padding: 2px 10px;
  color: #989898;
  font-size: 14px;
  border: 1px solid #989898;
  text-align: center;
}

.table-box {
  display: flex;
  flex: 1;
}

.photo {
  border: 2px solid white;
  box-sizing: border-box;
}

/* 大图遮罩层样式 */
.overlay {
  display: none;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  justify-content: center;
  align-items: center;
  z-index: 10000;
}

/* 大图样式 */
.big-img {
  max-width: 90%;
  max-height: 90%;
}

.overlay.show {
  display: flex;
}
</style>